<template>
  <div class="dept-container">
    <a-card>
      <!-- 搜索表单 -->
      <div class="search-form">
        <a-form
          :model="searchForm"
          layout="inline"
          @submit="handleSearch"
        >
          <a-form-item label="部门名称">
            <a-input
              v-model="searchForm.deptName"
              placeholder="请输入部门名称"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="状态">
            <a-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              allow-clear
            >
              <a-option :value="1">启用</a-option>
              <a-option :value="0">禁用</a-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" html-type="submit">
              <template #icon>
                <icon-search />
              </template>
              搜索
            </a-button>
            <a-button @click="handleReset">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-form-item>
        </a-form>
      </div>

      <!-- 操作按钮 -->
      <div class="table-actions">
        <a-button type="primary" @click="handleAdd">
          <template #icon>
            <icon-plus />
          </template>
          新增部门
        </a-button>
        <a-button
          type="outline"
          @click="toggleExpand"
        >
          <template #icon>
            <icon-menu-unfold v-if="!expandAll" />
            <icon-menu-fold v-else />
          </template>
          {{ expandAll ? '折叠' : '展开' }}全部
        </a-button>
      </div>

      <!-- 部门表格 -->
      <a-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="false"
        :expand-all-rows="expandAll"
        row-key="id"
      >
        <template #leader="{ record }">
          <span>{{ record.leader || '-' }}</span>
        </template>

        <template #status="{ record }">
          <a-switch
            v-model="record.status"
            :checked-value="1"
            :unchecked-value="0"
            @change="handleStatusChange(record)"
          />
        </template>

        <template #actions="{ record }">
          <a-button size="small" @click="handleEdit(record)">编辑</a-button>
          <a-button size="small" @click="handleAddChild(record)">新增</a-button>
          <a-popconfirm
            content="确定要删除这个部门吗？"
            @ok="handleDelete(record)"
          >
            <a-button size="small" status="danger">删除</a-button>
          </a-popconfirm>
        </template>
      </a-table>
    </a-card>

    <!-- 部门表单弹窗 -->
    <a-modal
      v-model:visible="formVisible"
      :title="formTitle"
      width="600px"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="上级部门" field="parentId">
              <a-tree-select
                v-model="formData.parentId"
                :data="deptTreeData"
                :field-names="{ key: 'id', title: 'deptName', children: 'children' }"
                placeholder="选择上级部门"
                allow-clear
                allow-search
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="部门名称" field="deptName">
              <a-input v-model="formData.deptName" placeholder="请输入部门名称" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="部门编码" field="deptCode">
              <a-input v-model="formData.deptCode" placeholder="请输入部门编码" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="显示排序" field="sort">
              <a-input-number v-model="formData.sort" placeholder="请输入排序" :min="0" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="负责人" field="leader">
              <a-input v-model="formData.leader" placeholder="请输入负责人" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="联系电话" field="phone">
              <a-input v-model="formData.phone" placeholder="请输入联系电话" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="邮箱" field="email">
              <a-input v-model="formData.email" placeholder="请输入邮箱" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="部门状态" field="status">
              <a-radio-group v-model="formData.status">
                <a-radio :value="1">正常</a-radio>
                <a-radio :value="0">停用</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="备注" field="remark">
          <a-textarea
            v-model="formData.remark"
            placeholder="请输入备注"
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { TableColumnData } from '@arco-design/web-vue'
import { deptApi } from '@/api'

// 搜索表单
const searchForm = reactive({
  deptName: '',
  status: undefined
})

// 表格数据
const tableData = ref([])
const deptTreeData = ref([])
const loading = ref(false)
const expandAll = ref(false)

// 表格配置
const columns: TableColumnData[] = [
  { title: '部门名称', dataIndex: 'deptName', width: 200 },
  { title: '部门编码', dataIndex: 'deptCode', width: 120 },
  { title: '排序', dataIndex: 'sort', width: 80 },
  { title: '负责人', slotName: 'leader', width: 100 },
  { title: '联系电话', dataIndex: 'phone', width: 120 },
  { title: '邮箱', dataIndex: 'email', width: 180 },
  { title: '状态', slotName: 'status', width: 80 },
  { title: '创建时间', dataIndex: 'createTime', width: 160 },
  { title: '操作', slotName: 'actions', width: 200, fixed: 'right' }
]

// 表单相关
const formVisible = ref(false)
const formTitle = ref('')
const formRef = ref()
const formData = reactive({
  id: undefined,
  parentId: 0,
  deptName: '',
  deptCode: '',
  leader: '',
  phone: '',
  email: '',
  sort: 0,
  status: 1,
  remark: ''
})

// 表单验证规则
const rules = {
  deptName: [
    { required: true, message: '请输入部门名称' },
    { minLength: 2, message: '部门名称至少2个字符' }
  ],
  deptCode: [
    { pattern: /^[a-zA-Z0-9_-]+$/, message: '部门编码只能包含字母、数字、下划线和横线' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址' }
  ]
}

// 搜索
const handleSearch = () => {
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    deptName: '',
    status: undefined
  })
  handleSearch()
}

// 切换展开
const toggleExpand = () => {
  expandAll.value = !expandAll.value
}

// 新增
const handleAdd = () => {
  formTitle.value = '新增部门'
  resetForm()
  formVisible.value = true
  fetchDeptTree()
}

// 新增子部门
const handleAddChild = (record: any) => {
  formTitle.value = '新增子部门'
  resetForm()
  formData.parentId = record.id
  formVisible.value = true
  fetchDeptTree()
}

// 编辑
const handleEdit = (record: any) => {
  formTitle.value = '编辑部门'
  Object.assign(formData, record)
  formVisible.value = true
  fetchDeptTree()
}

// 删除
const handleDelete = async (record: any) => {
  try {
    await deptApi.deleteDept(record.id)
    Message.success('删除成功')
    fetchData()
  } catch (error) {
    console.error('删除失败:', error)
  }
}

// 状态切换
const handleStatusChange = async (record: any) => {
  try {
    await deptApi.changeStatus(record.id, record.status)
    Message.success(`${record.status ? '启用' : '禁用'}成功`)
  } catch (error) {
    // 恢复原状态
    record.status = record.status ? 0 : 1
    console.error('状态切换失败:', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  const errors = await formRef.value?.validate()
  if (errors) return

  try {
    if (formData.id) {
      await deptApi.updateDept(formData.id, formData)
      Message.success('更新成功')
    } else {
      await deptApi.createDept(formData)
      Message.success('新增成功')
    }
    formVisible.value = false
    fetchData()
  } catch (error) {
    console.error('操作失败:', error)
  }
}

// 取消表单
const handleCancel = () => {
  formVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: undefined,
    parentId: 0,
    deptName: '',
    deptCode: '',
    leader: '',
    phone: '',
    email: '',
    sort: 0,
    status: 1,
    remark: ''
  })
  formRef.value?.clearValidate()
}

// 获取部门树数据
const fetchDeptTree = async () => {
  try {
    const response = await deptApi.getDeptTree()
    deptTreeData.value = [
      {
        id: 0,
        deptName: '顶级部门',
        children: response.data || []
      }
    ]
  } catch (error) {
    console.error('获取部门树失败:', error)
  }
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const response = await deptApi.getDeptList(searchForm)
    tableData.value = response.data || []
  } catch (error) {
    console.error('获取数据失败:', error)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style lang="scss" scoped>
.dept-container {
  padding: 20px;
}

.search-form {
  background: #f7f8fa;
  padding: 16px;
  border-radius: 6px;
  margin-bottom: 16px;
}

.table-actions {
  margin-bottom: 16px;
  
  .arco-btn + .arco-btn {
    margin-left: 8px;
  }
}
</style> 